define(['jquery', "controller", "mapController", "coordtransform","playback","plantController","select2","datetimepicker","rangeSlider","moment"], function ($) {

    var c = require("controller");
    var playback = require("playback");
    var mapController = require("mapController");
    var plantController=require("plantController");
    var coordtransform=require("coordtransform");
    var moment=require("moment");

    mapTools={
        isShowLine:function (pl) {
            pl.isShowLine=!pl.isShowLine;
            for (var did in pl.flights) {
                if (pl.isShowLine) {
                    pl.showLineById(did);
                } else {
                     pl.hideLineById(did);
                }
            }

        }
    };


    return {
        init: function () {
            var _this=this;
            var mapCenter=c.getValues("mapCenter")?c.getValues("mapCenter").split(','):[104.2272944, 30.5729027];//[104.2272944, 30.5729027]
            var mapZoom=parseInt(c.getValues("mapZoom"))||13;
            var mapStyle=c.getValues("mapStyle")?c.getValues("mapStyle").split(','):[];
            var map = mapController.initMap();
            var theight = $(window).height() - 50;
            $(".content").height(theight);

            map.init('container',{
                center:mapCenter,
                zoom:mapZoom
            });
            var Satellite=map.setMapType();
            map.setMapControl();
            $(".maptype>div:eq(0)").on('click',function () {
                Satellite.hide();
            });
            $(".maptype>div:eq(1)").on('click',function () {
                Satellite.show();
            });


            $.each(mapStyle,function (i,v) {
                mapStyle[i]=parseInt(v);
                $('input[value="'+v+'"]').prop("checked","checked");
            });

            var pl=new plantController.plane(map,playback);
            pl.isGuiji=true;

            var spaceLine=new plantController.drawSpaceLine(map,mapStyle);

            /*setInterval(function () {
                var ponints=ws.consumer_point();
                $.each(ponints,function (i,ponint) {
                    pl.initFlight(ponint);
                })

            },1000/ws.frame_num);*/
            map.addEventListener("mousemove", function (lnglat) {

                var lnglat84=coordtransform.gcj02towgs84(lnglat.lng,lnglat.lat)
                $('#hander-infos>.lng>span').text(mapController.changeLngToDMS(lnglat84[0]));
                $('#hander-infos>.lat>span').text(mapController.changeLatToDMS(lnglat84[1]));
            });

            map.addEventListener("zoomchange", function () {
                c.setValues("mapZoom",map.getZoom())
            });

            map.addEventListener("moveend", function () {
                var center=map.getCenter();
                c.setValues("mapCenter",[center.lng,center.lat])
            });

            //右侧工具
            $('.right-float-menu').on('click','div[data-event]',function () {
                $(this).toggleClass("selected");
                //$(this).parent().siblings().find('div').removeClass("selected");
            }).on('click','div[data-event="isFlightElements"]',function () {//开关飞行要素。
                 $('#elementspanel').toggle();
             });

            //开关空域要素
            $('#elementspanel').on('click','input',function (e) {
                var mapStyle=[];
                $('input[name="mapStyle"]:checked').each(function (e) {
                    mapStyle.push($(this).val());
                });
                c.setValues("mapStyle",mapStyle);
                if($(this).prop("checked")){
                    spaceLine.show($(this).val());
                }else{
                    spaceLine.hide($(this).val());
                }

            });

            $("#range_1").ionRangeSlider({
                min: moment("05:06", "HH:mm").format("X"),//+moment().subtract(1, "years").format("X"),
                max: moment("23:06", "HH:mm").format("X"),//+moment().format("X"),
                from: moment("05:06", "HH:mm").format("X"),
                prettify: function (num) {
                    return moment(num,'X').format("HH:mm:ss");
                },
                onChange: function (data) {
                    if(_this.isStart) {
                        window.clearInterval(c.plInterval);
                        $('.fa-play').removeClass('fa-pause');
                    }
                },
                onUpdate: function (data) {
                    if(data.from>=data.max){
                        window.clearInterval(c.plInterval);
                    }
                },
                onFinish: function (data) {
                    window.clearInterval(c.plInterval);
                    if(_this.isStart) {
                        playback.move(data.from);
                        $('.fa-play').addClass('fa-pause');
                        pl.GJrefresh();
                        bigrun();
                    }
                }
            });
            _this.rangeSlider=$("#range_1").data("ionRangeSlider");

            /**
             * 弹出框
             */
            showModel();
            function showModel() {
                $('#myModal').modal('show');
                $("#myModal>.modal-dialog").load("wstrack/form.html", function(){
                    _this.formInit(map,pl)
                });
            }
            $('#searchFlight').on('click',function () {
                showModel();
            });


            $('.big').on('click',function (e) {//开始播放
                window.clearInterval(c.plInterval);
                var $i=$(this).find('i');
                if(_this.isStart&&!$i.is('.fa-pause')){
                    pl.isShowLine=true;
                    bigrun();
                    $i.addClass('fa-pause');
                }else{
                    $i.removeClass('fa-pause');
                }
                if(!_this.isStart){
                    c.alert({
                        content:'没有相关数据'
                    })
                }


            });
            $('.back').on('click',function (e) {//减速
                if(_this.isStart){
                    window.clearInterval(c.plInterval);
                    playback.speeddown();
                    if($('.fa-play').is('.fa-pause')){
                        bigrun(true);
                    }

                }
            });

            $('.fast').on('click',function (e) {//加速
                if(_this.isStart){
                    window.clearInterval(c.plInterval);
                    playback.speedup();
                    if($('.fa-play').is('.fa-pause')){
                        bigrun(true);
                    }
                }
            });

            
            function  bigrun(isSet) {
                var i=1;
                var speed =playback.getspeed();
                $('.info').text('X'+speed);
                c.plInterval=setInterval(function () {
                    if(i==playback.frame_num||isSet){

                        _this.rangeSlider.update({
                            from:_this.rangeSlider.old_from+1*speed
                        });
                        isSet=false;
                        i=1;
                    }else{
                        i++
                    }
                    if(_this.isStart){
                        //playback.move(data.from);
                        var ponint=playback.consumer_point();
                        pl.initFlight(ponint);
                    }
                },(1000/playback.frame_num)/speed);
            }

        },
        wstrackData:null,
        rangeSlider:null,
        isStart:false,
        interval:null,
        formInit:function(map,pl){
            var _this=this;
            var Companys=c.getAllCompanys();
            var nn=[];
            $.each(Companys,function (i,v) {
                nn.push({id:v.cid,text:v.name})
            });
            $("#companys").select2({
                data:nn
            });
            setFid($("#companys").val());
            function setFid(cid) {//获取飞行器
                c.ajax({
                    url: "suggest/aircraft",
                    cache: false, //禁用缓存
                    data: {
                        cid:cid
                    }, //传入组装的参数
                    dataType: "json",
                    success: function (result) {
                        if (result.err==0){
                            var tempdata=[];
                            $.each(result.aircratfs,function (i,v) {
                                tempdata.push({id:v.fid,text:v.model})
                            });
                        }
                        $("#fid").empty();
                        $("#fid").select2({
                            data:tempdata
                        });
                    }
                });
            }
            $("#companys").on("change", function (e) {
                setFid($("#companys").val());
            });

            $('#flightday').datetimepicker({
                locale: 'zh-CN',
                format: 'YYYY-MM-DD',
                defaultDate:moment(c.serveDate,'X').format('YYYY-MM-DD'),
                maxDate:moment(c.serveDate,'X').format('YYYY-MM-DD')
            });
            $("#backbegin,#backend").datetimepicker({
                locale: 'zh-CN',
                format: 'HH:mm',
                defaultDate:moment(c.serveDate,'X').format('YYYY-MM-DD HH:mm'),
                maxDate:moment(c.serveDate,'X').format('YYYY-MM-DD HH:mm')
            });
           /* $("#backbegin,#backend").timepicker({showInputs: false,showMeridian:false});*/

            $('#wstrackButton').on('click',function (e) {
                window.clearInterval(c.plInterval);
                pl.remove();
                $('.fa-play').removeClass('fa-pause');
                _this.wstrackData= {
                    fid:$("#fid").val(),
                    flightday:$('#flightday').val(),
                    backbegin:$('#backbegin').val(),
                    backend:$('#backend').val()

                };
                if(_this.wstrackData.fid==""){
                    c.alert({
                        content:'请选择飞行器'
                    });
                    return false
                }
                if(_this.wstrackData.flightday==""){
                    c.alert({
                        content:'请选择起飞日期'
                    });
                    return false
                }
                if(_this.wstrackData.backbegin==""){
                    c.alert({
                        content:'请选择回放开始时间'
                    });
                    return false
                }
                if(_this.wstrackData.backend==""){
                    c.alert({
                        content:'请选择回放结束时间'
                    });
                    return false
                }
                if(moment(_this.wstrackData.backbegin, "HH:mm").format('X')>moment( _this.wstrackData.backend,"HH:mm").format('X')){
                    c.alert({
                        content:'开始时间不能大于结束时间'
                    });
                    return false
                }
                var min=moment(_this.wstrackData.flightday+" "+_this.wstrackData.backbegin, "yyyy-MM-dd HH:mm").format('X');
                var max=moment(_this.wstrackData.flightday+" "+_this.wstrackData.backend,"yyyy-MM-dd HH:mm").format('X');
                _this.rangeSlider.update({
                    min:min ,
                    max: max,
                    from:min
                });
                //_this.isStart=true;
                playback.connect(_this.wstrackData.fid,min,max,{
                    onopen:function () {
                        $('.ajaxLoading').show();
                    },
                    error:function () {
                        c.alert({
                            content:'查询失败'
                        });
                        $('.ajaxLoading').hide();
                    },
                    success:function (points) {
                        if(points.d.length>0){
                            _this.isStart=true;
                            var ponint=playback.consumer_point();
                            pl.initFlight(ponint);
                            map.setCenter([ponint.lng, ponint.lat]);
                            $('#myModal').modal('hide');
                            $('.rollback-footer').show();
                            $('.maptype').css('bottom','60px');
                        }else{
                            c.alert({
                                content:'没有飞行数据！'
                            });
                            $('.rollback-footer').hide();
                        }
                       $('.ajaxLoading').hide();

                    }
                });
            });
        }

    }

});


